var request = require('request');

//var sysApi = 'http://api.dev.wenshendaka.com';
var sysApi = 'http://api.wenshendaka.com';

var tagsLibrary = {
    '部位': '贴纸#几何#字符#动物#人物#植物#静物#鬼神#图腾#宗教#情侣#原创',
    '风格': '颈部#肩部#胸部#腹部#腰部#背部#臀部#手臂#腿部#手部#脚部',
    '元素': '欧美#传统#习俗#肖像#清新#写实#国画#手稿#男#女'
};

var JSONencode = function (str) {
    var encodeDisc = '\\\'\"';// '\'反斜杠必须第一个进行转义
    var char;
    for (var i in encodeDisc) {
        char = encodeDisc[i];
        str = str.replace(new RegExp('\\' + char, 'g'), '\\' + char);
    }
    return str;
};

var api = {
    getList: function (page, tag, $res) {

        var url = '';

        if (tag) {
            url = sysApi + "/new/web/gallery/index/?_method=GET&limit=30&index=" + (+page - 1) * 30 + "&tag=" + encodeURIComponent(tag);
        } else {
            url = sysApi + "/new/web/gallery/index/?_method=GET&limit=30&index=" + (+page - 1) * 30;
        }

        request(url, function (err, res, body) {

            try {
                var data = JSON.parse(body);

                if (data.code == 0) {
                    var list = [];
                    data = data.data;
                    var p, rev = 0;
                    for (var i = 0; i < data.list.length; i++) {
                        try {
                            p = data.list[i].image_urls[0].match(/_W_(\d*)X(\d*)$/);
                            if (p == null) {
                                data.list[i].height = 250;
                                data.list[i].imgUrl = data.list[i].image_urls[0] + '?imageView2/1/w/250/h/250/format/jpg/q/75';
                            }
                            else {
                                data.list[i].height = Math.ceil(250 * p[2] / p[1]);
                                data.list[i].imgUrl = data.list[i].image_urls[0] + '?imageView2/2/w/250/format/jpg/q/75';
                            }
                            list[i - rev] = {
                                _id: data.list[i]._id,

                                height: data.list[i].height,
                                imgUrl: data.list[i].imgUrl,

                                content: data.list[i].content,
                                visitCount: data.list[i].visitCount,
                                tagstring: (data.list[i].tag || '').split('#').join(' ')
                            }
                        }
                        catch (e) {
                            rev++;
                        }
                    }
                    var max = Math.ceil(data.count / 30);
                    var pageList = [], j;
                    for (i = +page - 5; i < +page + 5; i++) {
                        pageList.push(i);
                    }

                    $res.render('index', {
                        page: +page,
                        list: list,
                        max: max,
                        pageList: pageList,
                        tag: tag || '',
                        tagsLibrary: tagsLibrary,
                        json: JSONencode(JSON.stringify(list))
                    });

                } else {
                    $res.render('error', {
                        code: 500
                    });
                }
            } catch (e) {
                $res.render('error', {
                    code: 500
                });
            }

        });

    },
    getDetail: function (info, $res) {
        //info
        //  @id
        //  @from (?)

        var url = sysApi + "/new/web/gallery/detail/?_method=GET&_id=" + info.id;

        request(url, function (err, res, body) {
            console.log(body);
            try {
                var data = JSON.parse(body);

                if (data.code == 0) {
                    data = data.data;
                    $res.render('detail', {
                        content: data.detail.content || '',
                        tags: data.detail.tag || '',
                        images: data.detail.image_urls || [],
                        like_users: data.detail.like_users || [],
                        tagsLibrary: tagsLibrary,
                        from: info.from || '',
                        next: {
                            title: data.next.content || '',
                            link: data.next._id
                        },
                        previous: {
                            title: data.prev.content || '',
                            link: data.prev._id
                        },
                        recommend: data.random || []
                    });
                } else if (data.code == 404) {
                    api.getError($res, {
                        message: '这张图片不存在哦!',
                        random: data.random || []
                    });
                } else {
                    api.getError($res, {
                        code: 500,
                        random: data.random || []
                    });
                }
            } catch (e) {
                api.getError($res, {
                    code: 500
                });
            }
        });
    },
    getError: function ($res, info) {
        if (info && info.random && info.random.length > 0) {
            $res.render('error', {
                code: info.code,
                message: info.message,
                tagsLibrary: tagsLibrary,
                recommend: info.random || []
            });
        } else {
            request(
                sysApi + "/new/web/gallery/detail/?_method=GET&_id=0",
                function (err, res, body) {
                    try {
                        var data = JSON.parse(body);

                        data = data.data;
                        $res.render('error', {
                            code: info.code,
                            message: info.message || '',
                            tagsLibrary: tagsLibrary,
                            recommend: data.random || []
                        });
                    } catch (e) {
                        $res.render('error', {
                            code: 500,
                            message: info.message || '',
                            tagsLibrary: tagsLibrary,
                            recommend: []
                        });
                    }
                });
        }
    }
};

module.exports.getList = api.getList;
module.exports.getDetail = api.getDetail;
module.exports.getError = api.getError;